<template>
  <div style="padding: 15px;">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" >
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-form-item label="仓库" prop="warehouseCode">
              <el-select v-model="form.warehouseCode" filterable placeholder="请选择" @change="changeWarehouse">
                <el-option v-for="item in warehouseList" :key="item.value" :label="item.name" :value="item.code" />
              </el-select>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="16">
          <div class="grid-content bg-purple">
            <el-form-item label="备注" prop="shipmentCode">
              <el-input v-model="form.remarks" style="width:75%" />
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col >
          <el-button @click="chooseGoods">选择移位商品</el-button>
          <el-button :disabled="selectData.length === 0" @click="delGoods">删除</el-button>
        </el-col>
      </el-row>
    </el-form>
    <br>
    <vxe-table
      ref="xTable"
      border
      resizable
      stripe
      highlight-current-row
      show-overflow
      keep-source
      align="center"
      :edit-rules="validRules"
      max-height="600"
      row-id="id"
      :loading="loading"
      auto-resize
      :data="tableData"
      :edit-config="{trigger: 'click', mode: 'cell'}"
      :checkbox-config="{ highlight: true, range: true}"
      @checkbox-all="selectChangeEvent"
      @checkbox-change="selectChangeEvent"
    >
      <vxe-table-column type="checkbox" width="60"></vxe-table-column>
      <vxe-table-column type="seq" width="60" title="序号"></vxe-table-column>
      <vxe-table-column :visible=false field="inventoryCode" min-width="200" title="库存标识" :formatter="formatInventoryCode" />
      <vxe-table-column title="入驻商" field="shipmentName" min-width="200" />
      <vxe-table-column title="商品名称" field="goodsName" min-width="200" />
      <vxe-table-column field="goodCode" min-width="200" title="商品编码"  />
      <vxe-table-column field="goodsBarCode" title="商品条码" min-width="200"  />
      <vxe-table-column field="unitName" title="单位" min-width="80"  />
      <!-- <vxe-table-column field="totalQuantity" title="数量" min-width="80" :formatter="formatTotalQuantity" /> -->
      <vxe-table-column field="warehouseSpaceName" title="库区" min-width="200"  />
      <vxe-table-column field="locationName" title="移出库位" min-width="200"  />
      <!-- <vxe-table-column field="targetLocationName" title="移入库位" :edit-render="{name: 'ElSelect'}" width="270">
        <template v-slot:edit="{ row }">
          <locationElSelect ref="locationElSelect"  @setLocationCode="(data)=>{ setLocationCode(row, data) }"/>
        </template>
      </vxe-table-column> -->
      <vxe-table-column field="moveQuantity" title="移出数量" min-width="200" />
      <vxe-table-column field="gmtManufacture" title="生产日期" min-width="200"  />
      <vxe-table-column field="goodsStatusName" title="库存状态" min-width="200"  />
      <vxe-table-column field="isLock" title="锁定状态" min-width="200" :formatter="formatIsLock"  />
      <vxe-table-column field="remarks" title="备注" min-width="200"  />
    </vxe-table>
    <vxe-toolbar/>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="funcSave" plain>保存</el-button>
      <el-button type="primary" @click="funcSubmit" plain>提交</el-button>
    </div>

    <vxe-modal v-model="modelChooseInventoryFlag" title="选择移位商品"  width="1300" height="900" destroy-on-close>
      <moveChooseInventory :warehouseCode="form.warehouseCode" @fatherCancel="fatherCancel" @fatherAddItem="fatherAddItem" />
    </vxe-modal>
  </div>
</template>
<script>
  import Vue from "vue";
  import "xe-utils";
  import VXETable from "vxe-table";
  import "vxe-table/lib/index.css";
  import XEUtils from "xe-utils";
  import VXEUtils from "vxe-utils";
  import VXETablePluginElement from 'vxe-table-plugin-element'
  import 'vxe-table-plugin-element/dist/style.css'

  import moveChooseInventory from './components/moveChooseInventory';
  Vue.use(VXETable, VXEUtils, XEUtils, { mounts: ['cookie'] })
  VXETable.use(VXETablePluginElement)
  import { moveAdd } from "@/api/store";
  import { getWarehouse, getLocation } from "@/api/basicInfo";
  import { isNumber } from '@/utils/validate.js'
  import locationElSelect from '@/views/components/locationElSelect.vue'

  export default {
    name: "新增移位单",
    components: {
      moveChooseInventory,
      locationElSelect
    },

    data() {
      return {
        message: "",
        loading: false,
        tableData: [],
        locationData:[],
        code: "",
        itemListQuery: {
          //移位单号
          // moveCode: this.form.code,
          pageNum: 1,
          pageSize: 10,
          sortField: "",
          sortType: "",
        },
        validRules: {
          moveQuantity: [
            { required: true, message: '数量必须填写' },
            { pattern: /^[1-9]+[0-9]*$/, message: '数量必须大于0' },
            { max: 20, message: '数量不能超过20位'}
          ],
        },

        warehouseList: [],
        locationList: [],

        modelChooseInventoryFlag: false,

        form: {
          warehouseCode: "",
          warehouseName: "",
          totalQuantity: 0,
          remarks: "",
          status: 0,
          moveItemVOList: [],
        },
        rules:{
          warehouseCode: [
            { required: true, message: "请选择仓库", trigger: "blur" },
          ]
        },
        selectData: [], // 选中的数据
        autoValue: ''
      };
    },
    watch:{
      "form.warehouseCode":{
        handler:function(val,oldVal){
          // 改变仓库时，需要清空明细表格
          if(val != oldVal && oldVal != ""){
            this.$refs.xTable.remove();
          }
        },
      },
    },
    created() {
      this.findWarehouseList();
      // this.findLocationList();
      // this.selectWarehouseSpace()
    },
    methods: {
      // 根据选择的仓库加载仓库库区
      changeWarehouse(warehouseCode) {
        getLocation(warehouseCode).then(response => {
          this.locationData = response.data
        });
      },
    setLocationCode(row, data){
      row.targetLocationName = data.value
      row.targetLocation = data.code
      // row.targetLocation = obj
    },
    // 选择仓库库区
    selectWarehouseSpace() {
      getLocation().then(response => {
        this.locationData = response.data
      });
    },

      formatTotalQuantity({cellVal, row}){
        return row.quantity - row.useQuantity;
      },
      formatInventoryCode({cellVal, row}){
        return row.code;
      },
      formatIsLock({cellValue}){
        const isLockStaus = ['否', '是']
        return isLockStaus[cellValue]
      },

      getInfo(code) {
        this.code = code;
      },

      findWarehouseList(){
        getWarehouse().then((response)=>{
          this.warehouseList = response.data;
          if(this.warehouseList.length === 1){
            this.form.warehouseCode = this.warehouseList[0].code
            this.changeWarehouse(this.form.warehouseCode)
          }
        })
      },

      findLocationList(){
        const params = {'warehouseCode': this.form.warehouseCode}
        getLocation(this.form.warehouseCode).then((response)=>{
          const emptyItem = {'serialNumber':'--请选择--', 'code': ''};
          this.locationList.push(emptyItem);
          this.locationList = this.locationList.concat(response.data);
        })
      },
      // 选择库存
      chooseGoods(){
        if(this.form.warehouseCode == ""){
          this.$message.error('请选择仓库');
          return ;
        }
        this.modelChooseInventoryFlag = true;
      },

      // 添加明细
      fatherAddItem(data){
        if (data.length > 0) {
          data.forEach((item, idx) => {
            const result = this.tableData.filter(currentItem => currentItem.code === item.code)
            if (result.length === 0) {
              this.tableData.push(item)
            } else {
              let idx = this.tableData.indexOf(result[0])
              Object.assign(this.tableData[idx], item)
            }
          })
          this.$refs.xTable.clearScroll()
        }
        this.modelChooseInventoryFlag = false;
      },
    // 删除
    delGoods() {
      this.$confirm('确定要删除所选数据吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.selectData.forEach((item, idx) => {
              this.tableData.forEach((curItem, curIdx) => {
                if(curItem.code === item.code) {
                  this.tableData.splice(curIdx, 1)
                }
              })
          })
          setTimeout(()=>{
            this.selectData = []
          }, 100)
        })
        .catch(() => {
          // console.log('已取消，不加catch会报警告')
        })
    },

    fatherCancel(){
      this.modelChooseInventoryFlag = false;
    },

      // 保存
      funcSave(){
        // 校验数据
        this.$refs.form.validate((valid) => {

          if (valid) {
            let datas = this.$refs.xTable.getTableData().tableData;
            if(datas.length == 0){
              this.$message.error('请添加移位明细');
              return;
            }
            // 计算总数
            let totalQuantity = 0;
            for(let data of datas){
              if(isNumber(data.moveQuantity)){
                totalQuantity += Number(data.moveQuantity);
              }
            }
            this.form.totalQuantity = totalQuantity;
            this.form.moveItemVOList = this.tableData;
            this.funcSaveOrSubmit();
          }
        });
      },

      // 提交
      funcSubmit(){
        // 校验数据
        this.$refs.form.validate((valid) => {
          if (valid) {

            let datas = this.$refs.xTable.getTableData().tableData;
            if(datas.length == 0){
              this.$message.error('请添加移位明细');
              return;
            }

            // 计算总数
            let totalQuantity = 0;
            const count = datas.length;
            for(let i =0; i<count; i++){
              // 判断移入库位、移入数量是否填写；
                // datas[i].targetLocation == '' ||
              //   if(!isNumber(datas[i].moveQuantity) || Number(datas[i].moveQuantity) <0 ){
              //   this.$message.error(`第${i+1}行没有填写移位数量信息`);
              //   return ;
              // }

              if(isNumber(datas[i].moveQuantity)){
                totalQuantity += Number(datas[i].moveQuantity);
              }
            }
            this.form.totalQuantity = totalQuantity;
            this.form.moveItemVOList = this.tableData;

            this.form.status = 11;

            this.funcSaveOrSubmit();

          }
        });
      },

      //
      funcSaveOrSubmit(){
        const params = this.form;
        const rLoading = this.openLoading({
          text: '处理中...',
          duration: 'infinity'
        })
        moveAdd(params).then((response)=>{
          if(response.status == 0){
            this.$message({ message: '保存成功', type: 'success' });
            this.$eventBus.$emit('refreshList')
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({ path: "move" })
          }else{
            this.$message.error(response.msg);
          }
        }).finally(()=>{
          rLoading.close() // 关闭遮罩层
        })
      },

      // 排序
      sortList({ column, property, order }) {
        if (order) {
          this.itemListQuery.sortField = property;
          this.itemListQuery.sortType = order;
        } else {
          this.listQuery.sortField = "";
        }
        this.findMoveItemList();
      },
      // 全选与否，勾选、取消事件
      selectChangeEvent({ checked, selection }) {
        this.selectData = selection
      },
      // 分页handle
      handlePageChange({ currentPage, pageSize }) {
        this.itemListQuery.pageNum = currentPage;
        this.itemListQuery.pageSize = pageSize;
        this.findMoveItemList();
      },
      // 设置底部合计
      footerMethod({ columns, data }) {
        return [
          columns.map((column, columnIndex) => {
            if (columnIndex === 0) {
              return "合计";
            }
            if (["pageviews", "forecast"].includes(column.property)) {
              return XEUtils.sum(data, column.property);
            }
            return null;
          }),
        ];
      },
    },
  };
</script>

<style>
  .vxe-table .vxe-body--column:not(.col--ellipsis),
  .vxe-table .vxe-footer--column:not(.col--ellipsis),
  .vxe-table .vxe-header--column:not(.col--ellipsis) {
    padding: 6px 0;
  }
  .vxe-toolbar {
    padding: 0 0 10px 0;
  }
</style>
<style lang="scss" scoped>
  .dialog-footer {
    margin: 35px auto;
    width: 175px;
    // float: right;
  }
</style>
